<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2021/07/20
 * Time: 11:07
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\model\ProductKeyword;
use app\common\service\product\ProductService;
use think\facade\Validate;

/**
 * 关键词控制器
 * Class KeywordController
 * @package app\admin\controller\wms
 */
class KeywordController extends BaseController
{
    /**
     * 关键词首页
     * @date 2021/07/20
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $model = ProductKeyword::with(['category', 'admin' => function($query)
            {
                $query->field(["id", "nickname"]);
            }])->order("hot desc, used desc");
            $this->searchModel($model, [
                'eq' => ['type', 'status', 'hot'],
                'gt' => ['used'],
                'times' => ['create_time'],
                'like' => ['word'],
            ]);
            if($catId = $this->request->request("cate_id"))
            {
                $catIds = \app\common\model\ProductKeywordCategory::getAllSon($catId);
                $model->whereIn('cate_id', $catIds);
            }
            $limit = $this->getPageSize();
            $model = $model->paginate($limit);
            $this->assign('list', $model->getCollection());
            $this->assign('page', $model->render());
            return $this->fetch('lists');
        }
        $this->assign("is_show_import", $this->user->hasPermissions("/wms/keyword/import"));
        $this->assign("is_show_add", $this->user->hasPermissions("/wms/keyword/add"));
        $this->assign("category", \app\common\model\ProductKeywordCategory::getAllByTree());
        $this->assign("used", [5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000]);
        $this->assign("hot", range(1, 5));
        $this->assign("status", ["关闭", "启用"]);
        return $this->fetch('index');
    }

    /**
     * 添加更新关键词
     * @date 2021/07/20
     * @author longli
     */
    public function add()
    {
        $wordId = $this->request->get("word_id", "", "trim");
        if($word = ProductKeyword::get($wordId))
            $this->assign("word", $word);
        $this->assign("category", \app\common\model\ProductKeywordCategory::getAllByTree());
        $this->assign("types", ProductKeyword::$WORD_TYPE);
        $this->assign("hots", range(1, 5));
        return $this->fetch('add');
    }

    /**
     * 保存关键词
     * @date 2021/07/20
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'cate_id'  => 'require',
                'word' => 'require'
            ],[
                'cate_id.require' => '分类必选',
                'word.require' => '关键词必填',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = ProductKeyword::IS_NO;
        }
        else
        {
            $validate = Validate::make([
                'word_id'  => 'require',
            ],[
                'word_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['word_id', 'status', 'used'], 'get');
            if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
            if(isset($data['used']))
            {
                ProductKeyword::where("word_id", $data['word_id'])->setInc("used");
                $this->success('操作成功');
            }
        }
        ProductService::getInstance()->addKeyword($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 导入关键词
     * @date 2021/07/20
     * @author longli
     */
    public function import()
    {
        $file = $this->request->request("path");
        if(empty($file)) $this->error("非法请求");
        $file = ProductService::getRootPath($file);
        $keywordImport = new \app\common\service\import\Keyword($file);
        try
        {
            $keywordImport->run();
            return apiResponse(\app\common\status\BaseStatus::CODE_NORMAL, [], '导入成功');
        }catch(\RuntimeException $e)
        {
            $this->error($e->getMessage());
        }
    }

    /**
     * 删除关键词
     * @date 2021/07/20
     * @author longli
     */
    public function delete()
    {
        $ids = $this->request->request("ids");
        if(empty($ids)) $this->error('参数错误');
        ProductKeyword::destroy($ids);
        $this->success('删除成功');
    }
}